<template>
  <!-- 登录模态框 -->
  <div class="model">
    <!-- 
        mask 会有点击事件 关闭
        loginbox 后期也会有点击事件(关闭,登录)  都会触发mask
        此处在布局上解决冒泡的问题!
    -->
    <!-- 遮罩层 -->
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <!-- 登录内容 -->
    <div class="loginBox">
      <!-- 关闭按钮 -->
      <div class="close" @click="changeIsShowLoginModal(false)"></div>
      <section class="nav">
        <!-- 导航区域 -->
        <a
          href="#"
          :class="{ active: isShowContent }"
          @click="isShowContent = true"
          >手机号码登录</a
        >&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;
        <a href="#" :class="{ active: !isShowContent }" @click="showQrCode"
          >微信扫码登录</a
        >
      </section>
      <!-- 内容区域 -->
      <div class="content">
        <!-- 手机号码登录 内容 -->
        <div class="phoneLogin" v-show="isShowContent">
          <div class="row">
            <input
              type="text"
              class="ipt"
              placeholder="请输入手机号"
              v-model="phoneNumber"
              ref="phone"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              class="ipt"
              placeholder="请输入短信验证码"
              v-model="code"
            />
            <button class="btn btncode" @click="getcode" v-show="!isShowCount">
              获取验证码
            </button>
            <button class="btn btncode" v-show="isShowCount">
              {{ count + "s" }}
            </button>
          </div>
          <div class="row">
            <button class="btn btnlogin" @click="submitFn">登录</button>
          </div>
        </div>
        <!-- 微信扫码登录 内容 -->
        <div class="qrLogin" v-show="!isShowContent" id="weixin">
          微信扫码登录
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions } from "vuex";
import { validateTelephoneNumber } from "../utils/index.js";
import { SendSMSAPI, PhoneReginAPI,BindPhoneAPI,UserProfilesAPI } from "../request/api.js";
export default {
  data() {
    return {
      isShowContent: true,
      msg: "向右滑动",
      //手机号
      phoneNumber: "",
      //倒计时数字
      count: 2,
      //是否显示倒计时数字
      isShowCount: false,
      code: "",
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: "showModal/changeIsShowLoginModal",
      changeIsLogined: "loginStatus/changeIsLogined",
      changeIsShowToast: "showToast/changeIsShowToast",
    }),
    ...mapActions({
      asyncIsShowToast: "showToast/asyncIsShowToast",
      asyncChangeUserInfo:"userInfo/asyncChangeUserInfo"
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    // 倒计时函数
    countdown() {
      // 显示数字
      this.isShowCount = true;
      let timer = setInterval(() => {
        this.count--;
        if (this.count == 0) {
          // 停止定时器
          clearInterval(timer);
          this.count = 2;
          // 不显示数字
          this.isShowCount = false;
        }
      }, 1000);
      //问题:连续点击后 定时器过快效果.
      //解决: 开关思想,区分开按钮
    },
    //提取一个校验手机号和滑块验证码的方法 -- 复用  (获取验证码,登录)
    toVerify() {
      //手机号验证
      if (!validateTelephoneNumber(this.phoneNumber)) {
        // alert("请输入正确的手机号");
        // this.changeIsShowToast({
        //   show:true,
        //   msg:'请输入正确的手机号',
        //   type:"danger"
        // });
        // setTimeout(() => {
        //   this.changeIsShowToast({
        //     show:false
        //   });
        // },1000);
        this.asyncIsShowToast({
          show: true,
          msg: "请输入正确的手机号",
          type: "danger",
        });
        this.$refs.phone.focus();
        return false;
      }
      //  2.滑动验证不正确  提示
      if (this.msg == "向右滑动" || this.msg == "再试一次") {
        // alert("请滑动拼图验证码")
        this.asyncIsShowToast({
          show: true,
          msg: "请滑动拼图验证码",
          type: "danger",
        });
        this.$refs.phone.focus();
        return false;
      }
      return true;
    },
    // 获取验证码
    async getcode() {
      /* 
          业务逻辑梳理:
          1. 手机号要输入不正确   提示
          2. 滑块验证不正确       提示
          3. 验证通过了 
            3.1 发起请求获取验证码
            3.2 倒计时效果
      */
      // 1. 手机号要输入不正确   提示
      //  调用公共方法验证
      //2. 滑块验证不正确       提示
      if (!this.toVerify) {
        return;
      } //得到验证结果,如果为true才继续执行后面的代码
      //3. 验证通过了
      //3.1 发起请求获取验证码   ( api.js 组件中引入  组件内调用 [network,网络]--学会检查请求地址,请求参数,响应结果. )
      let res = await SendSMSAPI({
        phone: this.phoneNumber,
      });
      //如果拦截器返回了false后面不再执行
      if (!res) return;
      //发送成功后
      alert("发送验证码成功!");
      //3.2 倒计时效果
      //    定时器timer 自动的 减数字count
      this.countdown();
    },
    // 登录
    async submitFn() {
      //1. 手机号验证通过
      //2. 图片验证码通过
      if (!this.toVerify()) {
        return;
      }
      //3. 手机验证码通过 (此处只是判断是否为空)
      if (this.code.trim() == "") {
        // alert("请输入手机验证码!");
        this.asyncIsShowToast({
          show: true,
          msg: "请输入手机验证码",
          type: "danger",
        });
        this.$refs.phone.focus();
        return;
      }
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        console.log("发起绑定手机号请求...");
        res = await BindPhoneAPI({
          verifyCode: this.code,
          phone: this.phoneNumber,
          uuid,
        });
      } else {
        //4. 发起登录-请求  (api.js  组件引入  传参)
        console.log("发起登录请求了....");
        res = await PhoneReginAPI({
          verifyCode: this.code,
          phone: this.phoneNumber,
        });
      }
      if (!res)  return;
      // 4.1弹出登录成功
      // alert("登录成功");
      this.asyncIsShowToast({
        show: true,
        msg: "登录成功",
        type: "danger",
      });
      this.$refs.phone.focus();
      // 4.2储存token在本地储存中
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      // 4.3隐藏登录模态框
      this.changeIsShowLoginModal(false);
      // 4.4topbar中登录按钮要变成购物车
      this.changeIsLogined(true);
      // 微信绑定 1.删除uuid
      localStorage.removeItem("uuid");
      // 2.删除地址中的code
     uuid && this.$router.push(this.$router.path)
    //  登录成功后获取用户信息：
    let userRes = await UserProfilesAPI();
      // if (!userRes) return;
      // console.log("用户信息为",userRes);
      // 更新用户信息
      this.asyncChangeUserInfo()
    },
    showQrCode() {
      this.isShowContent = false;
      //获取二维码 并展示
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLGltcG93ZXJCb3ggLmluZm97DQogICAgZGlzcGxheTogbm9uZTsNCn0=",
      });
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
.model {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  bottom: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.4);
  }
  .loginBox {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    .close {
      position: absolute;
      right: 60px;
      top: 15px;
      height: 22px;
      width: 22px;
      background: url("../assets/img/close.png");
    }
  }
  .nav {
    display: flex;
    justify-content: center;
    padding-top: 50px;
    color: #999;
    a {
      text-decoration: none;
      color: #999;
      margin: 0, 10px;
      &.active {
        color: #000;
      }
    }
  }
  .content {
    width: 350px;
    margin: 20px auto 0;
    height: 300px;
    .phoneLogin {
      .row {
        display: flex;
        margin-bottom: 20px;
      }
      .ipt {
        flex: 1;
        height: 45px;
        padding-left: 10px;
        outline: none;
      }
      .btn {
        background-color: #0a328e;
        color: #fff;
        border: none;
        line-height: 45px;
        cursor: pointer;
      }
      .btncode {
        margin-left: 10px;
        width: 80px;
      }
      .btnlogin {
        width: 100%;
      }
    }
    .qrLogin {
      text-align: center;
    }
  }
}
</style>
